import { initialState } from "../../const/index";
import { getTextByCanvas } from "../canvas2Text";
import { generateRandomString } from "../index";

export function generateCateElementClassName(init?: any) {
  try {
    const wrapperElement = document.getElementsByClassName("el-collapse")?.[0];
    let maps: any = {};
    // 一级分类模糊文本匹配精确文本
    let noReal2RealMaps: any = {};
    // 精确到模糊
    let real2NoRealMaps: any = {};
    // 遍历所有一级类
    for (let i = 0; i < wrapperElement.children.length; i++) {
      let cateWrapper = wrapperElement.children[i];
      // 找到一级类下面，classname为 vw_between_center 的子元素的 innerText
      const cateOneText =
        (cateWrapper.getElementsByClassName("bet_title")?.[0]?.children?.[0] as HTMLElement).innerText;
      const cateOneTextRandomStr = generateRandomString();
      maps[cateOneText] = "random_class_" + cateOneTextRandomStr;
      let classNames = cateWrapper?.className?.split(" ");
      if (classNames?.find((it) => it.startsWith("random_class_"))) {
        classNames = classNames?.map((item) =>
          item.startsWith("random_class_")
            ? "random_class_" + cateOneTextRandomStr
            : item
        );
      } else {
        classNames?.push("random_class_" + cateOneTextRandomStr);
      }
      cateWrapper.className = classNames?.join(" ");
      // [] 盘口的分类通过查询dom来set一下，不然准确度非常差
      const regex = /[0-9a-zA-Z\u4e00-\u9fa5]/g;
      // 使用正则表达式匹配 中文 大小写 数字
      const matches = cateOneText?.match(regex);
      const vagueStr = matches?.join("") || '';
      console.log({ cateOneText }, { vagueStr });
      noReal2RealMaps[vagueStr] = cateOneText;
      real2NoRealMaps[cateOneText] = vagueStr;
    }
    return {
      maps,
      noReal2RealMaps,
      real2NoRealMaps
    }

  } catch (error) {
    init();
    return {
      maps: {},
      noReal2RealMaps: {},
      real2NoRealMaps: {}
    }
  }
}

export function appendDom({
  init,
  start,
  stopInterval,
  mockToggle,
  goMakeMoney,
  isMock,
}: {
  init: any,
  start: any,
  stopInterval: any,
  mockToggle: any,
  goMakeMoney: any,
  isMock: boolean,
}) {

  console.log("[zjymock:]", "append按钮");
  const fixedDiv = document.createElement("div");
  fixedDiv.className = "fixed-div";
  const style = document.createElement("style");
  style.textContent = initialState.styleFixedDiv;
  document.head.appendChild(style);
  document.body.append(fixedDiv);

  const hideAndShowButton = document.createElement("button");
  hideAndShowButton.innerText = "隐藏";
  hideAndShowButton.id = "hideAndShowButton";
  fixedDiv.append(hideAndShowButton);
  hideAndShowButton.addEventListener("click", () => {
    const hideAndShowButtonDom = document.getElementById("hideAndShowButton");
    if (hideAndShowButtonDom?.innerText === "隐藏") {
      hideAndShowButton.innerText = "展示";
      (document.getElementById("orders") as HTMLElement).style.display = "block";
    } else {
      hideAndShowButton.innerText = "隐藏";
      (document.getElementById("orders") as HTMLElement).style.display = "none";
    }
  });
  fixedDiv.append(hideAndShowButton);

  [
    {
      name: "init",
      onClick: init,
    },
    {
      name: "start",
      onClick: start,
    },
    {
      name: "结束定时器",
      onClick: stopInterval
    },
    {
      name: "getcanvas",
      onClick: async () => {
        const { textArr } = await getTextByCanvas();
        console.log({ textArr });
      },
    },
    {
      name: isMock ? "mock状态" : "非mock",
      onClick: mockToggle
    },
    {
      name: "goMakeMoney",
      onClick: async () => {
        const textArr = initialState.mockTextArr;
        await goMakeMoney(textArr);
      },
    },
    {
      name: `${isMock}: 是否mock`,
      type: "div",
      onClick: () => { },
    },
  ].forEach((item, index) => {
    if (item.type === "div") {
      const div = document.createElement("div");
      div.innerText = item.name;
      div.style.marginLeft = `${index * 6}px`;
      fixedDiv.append(div);
      return;
    }
    console.log(item);
    const button = document.createElement("button");
    button.innerText = item.name;
    button.style.marginLeft = `${index * 6}px`;
    fixedDiv.append(button);
    button.addEventListener("click", () => {
      item?.onClick();
    });
  });
}


export const sendLog = async (state: any) => {
  const sendLogDFS = async () => {
    if (!state) {
      return
    }
    const result = await fetch(initialState.uploadHost + '/sendLog', {
      method: 'POST', // 指定请求方法
      headers: {
        'Content-Type': 'application/json' // 设置内容类型为 JSON
      },
      body: JSON.stringify(state) // 将 state 对象转换为 JSON 字符串并作为请求体
    })

    const res = await result.json();
    console.log({ res });
  }

  sendLogDFS();
  setInterval(() => sendLogDFS, 60 * 10 * 1000);
}

export const judgeLogin = (isMock: boolean) => {
  if (isMock) {
    return true;
  }
  // 判断一下是否需要登录
  const loginBtn = document.getElementsByClassName(
    "el-button el-button--default el-button--mini login_btn radius_10"
  )?.[0];
  if (loginBtn) {
    window.location.href = "/#/login";
    console.log("[zjymock:]", "运行脚本先请登录！");
    return false;
  }
  return true;
}